//验证二叉搜索树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    long long ret;

public:
    bool isValidBST(TreeNode* root) {
        ret = -2147483649;
        return dfs(root);
    }
    bool dfs(TreeNode* root) {
        if (!root)
            return true;
        bool left = dfs(root->left);
        if (root->val <= ret)
            return false;
        ret = root->val;
        bool right = dfs(root->right);
        return left && right;
    }
};


// 二叉搜索树中第 K 小的元素
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
    vector<int> nums;
    int ret;

public:
    int kthSmallest(TreeNode* root, int k) {
        dfs(root);
        ret = nums[k - 1];
        return ret;
    }
    void dfs(TreeNode* root) {
        if (!root)
            return;

        dfs(root->left);
        nums.push_back(root->val);
        dfs(root->right);
    }
};